import React, { useState, useRef, useEffect } from 'react';
import { Button, Table, Select, Input, DatePicker, Modal, message } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import style from './Seckill.module.css'
import Store from "./../../store/index"
import CreateExcel from 'js-export-excel';

const SeckillViews = () => {
    const [messageApi, contextHolder] = message.useMessage();
    const [columns, setColumns] = useState([
        { title: 'ID', dataIndex: 'id' },
        { title: '活动名称', dataIndex: 'name' },
        {
            title: '活动时间',
            dataIndex: 'time',
        },
        { title: '商品数', dataIndex: 'quantity' },
        { title: '秒杀状态', dataIndex: 'state' },
        { title: '上线状态', dataIndex: 'zt' },
        {
            title: '操作',
            dataIndex: '',
            width: '152px',
            render: (text) => (
                <div>
                    {contextHolder}
                    <Button type="link" onClick={() => edit(text)}>编辑</Button>
                    <Button type="link" onClick={() => shanChu(text)}>删除</Button>
                </div>
            )
        }
    ])
    const [data, setData] = useState(Store.getState().marketing.arr)
    const inRef = useRef()
    const [option1, setOption1] = useState([
        { value: '0', label: '全部' },
        { value: '1', label: '未开始' },
        { value: '2', label: '进行中' },
        { value: '3', label: '已结束' }
    ])
    const [option2, setOption2] = useState([
        { value: '0', label: '全部' },
        { value: '1', label: '上线中' },
        { value: '2', label: '已下线' },
    ])
    const shanChu = (b) => {
        Modal.confirm({
            title: '删除',
            icon: <ExclamationCircleOutlined />,
            content: '您确定要删除吗？',
            okText: '确认',
            cancelText: '取消',
            onOk() {
                data.forEach((el, index) => {
                    if (el.key === b.key) {
                        data.splice(index, 1)
                        const arr = [...data]
                        setData(arr)
                    }
                })
                messageApi.open({
                    type: 'success',
                    content: '删除成功',
                });
            },
            onCancel() {
                messageApi.open({
                    type: 'error',
                    content: '删除失败',
                });
            }
        })
    }
    const [size, setSize] = useState('large');
    const [time1, setTime1] = useState()
    const [time2, setTime2] = useState()
    const onChange = (value, dateString) => {
        // console.log('Formatted Selected Time: ', dateString);
        setTime1(dateString)
    };
    const onChange1 = (value, dateString) => {
        // console.log('Formatted Selected Time: ', dateString);
        setTime2(dateString)
    };
    const download = () => {
        let a = {}
        let dataTable = []
        a.fileName = '秒杀';
        data.map(el => {
            dataTable.push({
                'ID': el.id,
                '活动名称': el.name,
                '活动时间': el.time,
                '商品数': el.quantity,
                '秒杀状态': el.state,
                '上线状态': el.zt,
            })
        });
        a.datas = [
            {
                sheetData: dataTable,
                sheetName: 'sheet',
                sheetFilter: ["ID", "活动名称", "活动时间", "商品数", "秒杀状态", "上线状态"],
                sheetHeader: ["ID", "活动名称", "活动时间", "商品数", "秒杀状态", "上线状态"],
            }
        ];
        let toExcel = new CreateExcel(a);
        toExcel.saveExcel()
    }
    let [select1, setSelect1] = useState('')
    let [select2, setSelect2] = useState('')
    const handleChange1 = (e) => {
        setSelect1(option1[e].label)
    }
    const handleChange2 = (e) => {
        setSelect2(option2[e].label)
    }
    const [copy, setCopy] = useState([])
    useEffect(() => {
        setCopy([...data])
    }, []);
    const Search = () => {
        let a = inRef.current.input.value
        let b = select1
        let c = select2
        let e = time1 + time2
        // console.log(e)
        let arr = []
        if (b === '全部') {
            b = ''
        }
        if (c === '全部') {
            c = ''
        }
        copy.forEach(el => {
            const condition = (!a || el.name.includes(a)) &&
                (!b || el.state.includes(b)) && (!c || el.zt.includes(c)) &&
                (!e || el.time.includes(e))
            if (condition) {
                arr.push(el)
            }
        })
        if (a === '' && b === '' && c === '' && e === '') {
            arr = [...copy]
        }
        setData(copy)
        setData(arr)
    }
    const navigate = useNavigate()
    const addTo = () => {
        navigate('SeckillCV', { state: { title: '新建秒杀', txFb: true } })
    }
    const edit = (obj) => {
        console.log(obj)
        obj.title = '编辑秒杀'
        obj.txFb = false
        navigate('SeckillCV', { state: obj })
    }
    return (
        <div>
            <div className={style.box}>
                <Button type="primary" size={size} onClick={addTo} >新建秒杀</Button>
            </div>
            <div className={style.box1}>
                <div className={style.shuRu}>
                    <div style={{ marginRight: '50px' }}>
                        <span className={style.mc}>活动名称</span>
                        <Input placeholder="请输入名称" style={{ width: 201 }} ref={inRef} />
                    </div>
                    <div>
                        <span className={style.mc}>活动时间</span>
                        <DatePicker showTime onChange={onChange} />
                        <span style={{ margin: '0 10px' }}>至</span>
                        <DatePicker showTime onChange={onChange1} />
                    </div>
                </div>
                <div className={style.shuRu} style={{ marginTop: '20px' }}>
                    <div style={{ marginRight: '50px' }}>
                        <span className={style.mc}>活动状态</span>
                        <Select
                            showSearch
                            style={{
                                width: 166,
                            }}
                            onChange={handleChange1}
                            placeholder="请选择类型"
                            optionFilterProp="children"
                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                            filterSort={(optionA, optionB) =>
                                (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
                            }
                            options={option1}
                        />
                    </div>
                    <div>
                        <span className={style.mc}>上线状态</span>
                        <Select
                            showSearch
                            style={{
                                width: 166,
                            }}
                            onChange={handleChange2}
                            placeholder="请选择类型"
                            optionFilterProp="children"
                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                            filterSort={(optionA, optionB) =>
                                (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
                            }
                            options={option2}
                        />
                    </div>
                </div>
                <div className={style.an}>
                    <Button style={{ width: 89 }} type="primary" onClick={Search} size={size}>搜索</Button>
                    <Button style={{ width: 89 }} size={size} onClick={download}>导出</Button>
                </div>
            </div>
            <div className={style.box2}>
                <Table columns={columns} dataSource={data} pagination={{ pageSize: 5, total: data.length, showTotal: total => `共${total}条`, showQuickJumper: true }} />
            </div>
        </div>
    );
}

export default SeckillViews;
